package com.example.asus.happy;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.asus.happy.service.address.Address;
import com.example.asus.happy.service.application.MyApplication;
import com.example.asus.happy.service.finaldata.FinalData;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import static com.example.asus.happy.service.finaldata.FinalData.RESULT_LOAD_IMAGE;


public class SendActivity extends AppCompatActivity implements View.OnClickListener{
    //请求的URL
    private String url;
    //Intent
    private Intent intent;
    //左上角返回
    private TextView backTV;
    //以此为添加按钮，发送按钮，删除按钮
    private Button addImgBtn,sendBtn,delImgBtn;
    //用户选择的图片
    private ImageView imageView;
    //用户输入的笑话
    private EditText contextET;

    //初始化控件
    public void init(){
        backTV = (TextView)findViewById(R.id.backTV);
        addImgBtn = (Button)findViewById(R.id.addImgBtn);
        imageView = (ImageView) findViewById(R.id.imageView);
        sendBtn = (Button)findViewById(R.id.sendBtn);
        delImgBtn = (Button)findViewById(R.id.delImgBtn);
        contextET = (EditText)findViewById(R.id.contextET);
    }

    //Handler
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    String response = (String)msg.obj;
                    if (FinalData.ONE_STRING.equals(response)){
                        Toast.makeText(SendActivity.this, FinalData.ADD_SUCC, Toast.LENGTH_SHORT).show();
                        finish();
                    }
                    break;
                default:
                    Toast.makeText(SendActivity.this, FinalData.NONETWORK, Toast.LENGTH_SHORT).show();
                    break;
            }
        }

    };

    //与服务器建立连接
    private void HttpPostRequest(final String url){
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                try{
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    if (httpResponse.getStatusLine().getStatusCode() == FinalData.TWO_HUNDRED){
                        HttpEntity httpEntity = httpResponse.getEntity();
                        String count = EntityUtils.toString(httpEntity,FinalData.CODE);
                        Message message = new Message();
                        message.what = FinalData.ZERO_INT;
                        message.obj = count.toString();
                        handler.sendMessage(message);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //页面构建
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send);
        //调用初始化方法
        init();
        //返回按钮点击事件
        backTV.setOnClickListener(this);
        //选择图片按钮
        addImgBtn.setOnClickListener(this);
        //发送按钮点击事件
        sendBtn.setOnClickListener(this);
        //删除按钮点击事件
        delImgBtn.setOnClickListener(this);
    }

    //实现接口的点击事件方法
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.backTV :
                //关闭此界面
                finish();
                break;
            case R.id.addImgBtn :
                //调用本地图库
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, FinalData.RESULT_LOAD_IMAGE);
                break;
            case R.id.sendBtn :
                //获取用户输入笑话内容
                String context = contextET.getText().toString();
                /**
                 * 从application获取userName
                 * 如果userName为null跳转到登录，否则执行发布内容
                 */
                String userName = getApp().getUserName();
                if (!FinalData.NULL.equals(userName)){
                    if ("".equals(context)){
                        Toast.makeText(this, FinalData.NOCONTENT, Toast.LENGTH_SHORT).show();
                    }else {
                        //向服务器发送添加请求
                        url = Address.ADDRESS+"addAndroids?c_ct="+context+"&u_userName="+userName;
                        HttpPostRequest(url);
                    }

                }else {
                    Toast.makeText(this, FinalData.NOLOGIN, Toast.LENGTH_SHORT).show();
                    //跳转到登录界面
                    intent = new Intent(this,LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.delImgBtn :
                //删除配图
                imageView.setWillNotDraw(true);
                break;
        }
    }

    //将图片加载至imageView
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            //imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
            imageView.setWillNotDraw(false);
            imageView.setImageURI(selectedImage);
            //sendBtn.setText(picturePath);
        }
    }

    //获取application
    public MyApplication getApp(){
        return (MyApplication) getApplicationContext();
    }
}
